<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>json的序列化与自定义</title>
</head>

<body>

</body>
<script>
  // json的序列化结果
  "use strict"; {
    let obj = {
      title: "后盾人",
      age: 19,
      teacher: {
        name: "yc"
      },
    };
    let json = JSON.stringify(obj, ["title", "age"], 2);
    console.log(json);
  };
</script>
<script>
  // 使用toJSON的方法自定义返回JSON的数据格式
  "use strict"; {
    let obj1 = {
      url: `baidu.com`,
      name: "yc",
      text: {
        title: `放水的了吧`
      },
      toJSON() {
        return {
          cy_url: `${this.url}_cy`,
          cy_name: `${this.name}_cc`,
        }
      }
    };
    let i = JSON.stringify(obj1, null, 2);
    console.log(i);

    // JSON.parse将json数据解析，可以使用一个匿名函数的了
    let j = JSON.parse(i, (key, value) => {
      if (key == "cy_name") {
        value = `[一诚]_${value}`;
      };
      return value;
    });

    console.log(`json的数据解析了吧`, j);
  }; {
    "use strict"; {
      let obj = {
        name: "cz",
        age: 19,
        hobdy: ["打球", "看书", "写字", "读书"],
        sing: {
          "name": "李香兰",
          "song": "刘德华"
        },
        sayhai() {
          console.log(this.name);
        },
      };
      JSON.stringify(obj, (key, value) => {
        // if (typeof (value) == "function") return value.toString();
        console.log(key);
        console.log(value);
        return value;
      });
    };
  };
</script>

</html>